package com.sun.gis.tools.gdal;

import org.gdal.gdal.gdal;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Driver;
import org.gdal.gdalconst.gdalconstConstants;
import org.gdal.ogr.ogr;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Layer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;

public class GdalExample {
    public static void main(String[] args) {
        // 注册所有驱动
        gdal.AllRegister();
        ogr.RegisterAll();

        // 加载GeoJSON文件
        String geojsonPath = "D:\\data\\gdal\\320102.geojson";
        DataSource geojson = ogr.Open(geojsonPath, 0);
        if (geojson == null) {
            System.err.println("Failed to open GeoJSON file.");
            return;
        }

        Layer layer = geojson.GetLayer(0);
        if (layer == null) {
            System.err.println("Failed to get layer from GeoJSON file.");
            geojson.delete();
            return;
        }

        // 获取GeoJSON的边界框
        double[] extent = layer.GetExtent();
        if (extent == null || extent.length != 4) {
            System.err.println("Failed to get extent from GeoJSON layer.");
            geojson.delete();
            return;
        }
        double xmin = extent[0];
        double ymin = extent[2];
        double xmax = extent[1];
        double ymax = extent[3];

        // 栅格化GeoJSON到磁盘文件
        try {
            String geojsonRasterPath = "D:\\data\\gdal\\geojson_raster.tif";  // 栅格化输出路径
            String gdalRasterizePath = "D:\\soft\\gdal\\bin\\gdal\\apps\\gdal_rasterize.exe";  // 替换为GDAL安装路径
            String[] rasterizeCmd = {
                    gdalRasterizePath,
                    "-burn", "255", "-burn", "0", "-burn", "0",
                    "-ts", "1024", "1024",
                    "-te", String.valueOf(xmin), String.valueOf(ymin), String.valueOf(xmax), String.valueOf(ymax),
                    "-ot", "Byte",
                    "-of", "GTiff",
                    "-co", "COMPRESS=LZW",
                    "-l", layer.GetName(), geojsonPath, geojsonRasterPath
            };
            ProcessBuilder pb = new ProcessBuilder(rasterizeCmd);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                System.err.println("gdal_rasterize command failed with exit code " + exitCode);
                geojson.delete();
                return;
            }

            // 检查栅格化文件是否存在
            File rasterFile = new File(geojsonRasterPath);
            if (!rasterFile.exists()) {
                System.err.println("Rasterized file does not exist: " + geojsonRasterPath);
                geojson.delete();
                return;
            }

            // 将栅格化的GeoJSON转换为PNG图片
            Dataset rasterDataset = gdal.Open(geojsonRasterPath, gdalconstConstants.GA_ReadOnly);
            if (rasterDataset == null) {
                System.err.println("Failed to open rasterized GeoJSON.");
                geojson.delete();
                return;
            }

            String pngPath = "D:\\data\\gdal\\geojson_output.png";
            Driver pngDriver = gdal.GetDriverByName("PNG");
            Dataset pngDataset = pngDriver.CreateCopy(pngPath, rasterDataset);
            if (pngDataset == null) {
                System.err.println("Failed to create PNG image.");
                rasterDataset.delete();
                geojson.delete();
                return;
            }

            // 关闭数据集
            rasterDataset.delete();
            pngDataset.delete();

            System.out.println("GeoJSON已成功渲染为PNG图片: " + pngPath);

        } catch (Exception e) {
            e.printStackTrace();
            geojson.delete();
        }
    }
}
